﻿using Newtonsoft.Json;
using RXY_Mall.AdminApi.Common;

using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services;
using RXY_Mall.Services.Manager;
using RXY_Mall.Services.Manager.Dto;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;

namespace RXY_Mall.AdminApi.Controllers
{
    /// <summary>
    /// 公司接口
    /// </summary>
    [RoutePrefix("Manager")]
    [ApiSecurityFilter]
    public class ManagerController : BaseApiController
    {
        public IManagerService managerService;

        public ManagerController()
        {
            managerService = new ManagerService();
        }

        #region 管理员
        /// <summary>
        /// 批量添加管理员
        /// </summary>
        /// <param name="input">输入信息</param>
        [HttpPost]
        [Route("AddManagers")]
        public async Task<ResponseService<bool>> AddManagers(AddManagersInput input)
        {
            return await managerService.AddManager(input);
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Login")]
        public async Task<ResponseService<LoginOutput>> Login(LoginInput input)
        {
            ResponseService<LoginOutput> result = new ResponseService<LoginOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                if (input.user_name != "rxymall")
                {
                    result.msg = "无权限";
                    return result;
                }

                var manager = await managerService.GetManager(input);

                if (manager.code != 1)
                {
                    result.msg = manager.msg;
                    return result;
                }
                result = SetToken(manager.data);
                result.msg = "登录成功";
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 设置ManagerToken
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ResponseService<LoginOutput> SetToken(LoginOutput input)
        {
            ResponseService<LoginOutput> result = new ResponseService<LoginOutput>();
            LoginOutput output = new LoginOutput()
            {
                manager_id = input.manager_id,
                user_name = input.user_name,
                token = input.token,
            };

            SignExtension.SetToken(input.manager_id, input.token);
            result.code = 1;
            result.data = output;
            return result;
        }
        #endregion
    }
}
